/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-10-24     hehung       the first version
 */
#include "app_uart.h"
#include "board.h"

#include <rtthread.h>
#include <stddef.h>
#include "app_oled.h"
#include "app_esp8266.h"

#define UART1_DIS                        0u
#define UART1_EN                         1u
#define UART1_DEBUG                      UART1_EN

#if(UART1_DEBUG == UART1_EN)
#define SAMPLE_UART_NAME                 "uart1"
#endif
#define DATA_CMD_END                     '\r'       /* 结束位设置为 \r，即回车符 */
#define ONE_DATA_MAXLEN                  64         /* 不定长数据的最大长度 */

/* 用于接收消息的信号量 */
static struct rt_semaphore rx_sem;
static rt_device_t serial;

char data[ONE_DATA_MAXLEN];
uint8_t uart_reveiced_finished = 0u;

static rt_err_t uart_rx_ind(rt_device_t dev, rt_size_t size);
static char uart_sample_get_char(void);
static void data_parsing(void);
#if(UART1_DEBUG == UART1_EN)
static int uart_data_sample(int argc, char *argv[]);
#endif

void UART1_AppInit(void)
{
    rt_err_t ret = RT_EOK;
    char uart_name[RT_NAME_MAX] = {"uart1"};

    /* 查找系统中的串口设备 */
    serial = rt_device_find(uart_name);
    if (!serial)
    {
        rt_kprintf("ERROR: UART1 Find %s Failed!\n", uart_name);
    }

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_rx_ind);

    /* 创建 serial 线程 */
    rt_thread_t thread = rt_thread_create("Serial Thread Manage",
                                         (void (*)(void *parameter))data_parsing,
                                         RT_NULL,
                                         2048,
                                         1,
                                         10);
    /* 创建成功则启动线程 */
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
    }
    else
    {
        ret = RT_ERROR;
    }
}

/* 接收数据回调函数 */
static rt_err_t uart_rx_ind(rt_device_t dev, rt_size_t size)
{
    char ch;
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    if (size > 0)
    {
//        rt_kprintf("-->%d-->", size);
        rt_sem_release(&rx_sem);
    }

    return RT_EOK;
}

static char uart_sample_get_char(void)
{
    char ch;

    while (rt_device_read(serial, 0, &ch, 1) == 0)
    {
        rt_sem_control(&rx_sem, RT_IPC_CMD_RESET, RT_NULL);
        rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
    }

    return ch;
}

/* 数据解析线程 */
static void data_parsing(void)
{
    char ch;
    static char i = 0;

    while (1)
    {
        ch = uart_sample_get_char();
        i = (i >= ONE_DATA_MAXLEN-1) ? ONE_DATA_MAXLEN-1 : i;
        data[i++] = ch;
//        rt_device_write(serial, 0, &ch, 1);
        if(ch == DATA_CMD_END)
        {
            data[i++] = '\0';
//            rt_kprintf("Uart1.RX:-->%s\n",data);
            ESP8266_RecvDataProcess(data);
//            if(data[0] == 'A')
//                OLED_SetDisplayFlag(0);
                //暂停OLED线程，节约CPU，用于接受后续的数据
            i = 0;
            rt_device_read(serial, 0, &ch, 1);
            uart_reveiced_finished = 1u;
            continue;
        }
    }
}

void UART1_SendUart1Data(const void *buffer, uint8_t len)
{
    rt_device_write(serial, 0, buffer, len);
}

char UART1_ReadCharFromFIFO(void)
{
    char ch;
    rt_device_read(serial, 0, &ch, 1);
    return ch;
}

#if(UART1_DEBUG == UART1_EN)
static void uart1_at_cmd(int argc, char**argv)
{
//    char str[] = "AT\r\n";
    char *str = NULL;

    if(!rt_strcmp(argv[1], "AT"))
    {
        str = rt_malloc((argc+2)*sizeof(char));
        rt_sprintf(str,"%s\r\n", argv[1]);
//        str = rt_strncpy(str, argv[1], argc);
//        str = strcat(str, "\r\n");
        /* 发送字符串 */
        rt_device_write(serial, 0, str, (sizeof(str)));
        rt_free(str);
    }
    else if(!rt_strcmp(argv[1], "AT"))
    {

    }
    else
    {
        rt_kprintf("AT command via Uart1: uart1_at_cmd <AT command>\n");
    }
}
MSH_CMD_EXPORT(uart1_at_cmd, AT command via Uart1: uart1_at_cmd <AT command>);

static int uart_data_sample(int argc, char *argv[])
{
    rt_err_t ret = RT_EOK;
    char uart_name[RT_NAME_MAX];
    char str[] = "hello RT-Thread!\r\n";

    if (argc == 2)
    {
        rt_strncpy(uart_name, argv[1], RT_NAME_MAX);
    }
    else
    {
        rt_strncpy(uart_name, SAMPLE_UART_NAME, RT_NAME_MAX);
    }

    /* 查找系统中的串口设备 */
    serial = rt_device_find(uart_name);
    if (!serial)
    {
        rt_kprintf("find %s failed!\n", uart_name);
        return RT_ERROR;
    }

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_rx_ind);
    /* 发送字符串 */
    rt_device_write(serial, 0, str, (sizeof(str) - 1));

    /* 创建 serial 线程 */
    rt_thread_t thread = rt_thread_create("serial", (void (*)(void *parameter))data_parsing, RT_NULL, 1024, 1, 10);
    /* 创建成功则启动线程 */
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
    }
    else
    {
        ret = RT_ERROR;
    }

    return ret;
}

/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(uart_data_sample, uart device sample);
#endif

